import MapUtil from '@/utils/map/mapLayerUtil'
import CountryGasPopup from '@/components/MapPopup/CountryGasPopup.vue'

import { useGlobalStore } from '@/store/global'
const globalStore = useGlobalStore()

// 添加点位图层
export const addTestGroupOnePointLayer = async (item: any) => {
    const result = await getWgmsSitesByQuery(item)
    const { data, code } = result as { data: any; code: string }
    const { jsonData, icon } = buildGeoJSONData(data, code)
    MapUtil._addSourceToMap(item, jsonData)
    MapUtil._addImageToMap(`icon/`, icon, '.png', '')
    const symbolLayerName = MapUtil._renderMapLayer({
        id: item,
        type: 'symbol',
        source: item,
        layout: {
            'icon-image': '{symbolImgName}',
            'icon-ignore-placement': true,
            'icon-size': 0.7
        }
    })
    if (symbolLayerName) {
        MapUtil._addHoverEventToLayer(symbolLayerName, 'name')
        addClickEventToLayer(symbolLayerName)
    }
}

// 根据传入的图层做地图点位的筛选
const getWgmsSitesByQuery = (layerId: string) => {
    return new Promise(resolve => {
        // 示例点位
        resolve({ data: [{
            "wd": "30.163416787723637",
            "jd": "120.26964053980008",
            "name": "国控站"
        }], code: layerId })
    })
}

/**
 * 构造GeoJSON数据，给每个属性增加symbolName字段（该字段用于匹配图标）
 */
export const buildGeoJSONData = (data: any[], code: string) => {
    const icon = [] as string[]
    const GeoJsonHeader = {
        type: 'FeatureCollection',
        crs: {
            type: 'name',
            properties: {
                name: 'urn:ogc:def:crs:OGC:1.3:CRS84'
            }
        },
        features: [] as any[]
    }
    data.forEach(point => {
        if (!point.jd || !point.wd) { return }
        const lon = parseFloat(point.jd)
        const lat = parseFloat(point.wd)
        const coordinates = lon > lat ? [lon, lat] : [lat, lon]
        point.symbolImgName = `${code}${point.status ? `-${point.status}` : ''}`
        if (!icon.includes(point.symbolImgName)) icon.push(point.symbolImgName)
        const featureItem = {
            type: 'Feature',
            properties: {
                ...point,
                coordinates: coordinates
            },
            geometry: {
                type: 'Point',
                coordinates: coordinates
            }
        }
        GeoJsonHeader.features.push(featureItem)
    })
    return { jsonData: GeoJsonHeader, icon: icon }
}

// 添加弹窗点击事件
const addClickEventToLayer = (layerName: string) => {
    window.glMap.on('click', layerName, (e: any) => {
        const properties = e.features[0].properties
        const coordinates = JSON.parse(properties.coordinates)
        console.log(layerName, coordinates)
        const SubPopup = {
            country: {
                component: CountryGasPopup,
                height: 300
            }
        }[layerName]
        if (SubPopup) {
            window.popContent = createApp(SubPopup.component, {
                properties: properties
            })
            const parent = document.createElement('div')
            const $el = window.popContent.mount(parent).$el
            MapUtil._showPopupOnMap(coordinates, $el, SubPopup.height, [0, -15])
        }
    })
}
